package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid

import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.album.view.grid_view.XGridLayout
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.PixUtils
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.SstShopOrderChild
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.MyOrderListLab
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid.bean.*
import com.example.wallet.db.UserInfoManager
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

/**
 * 全部
 * */
class SubMyOrderAllFragment(override val orderStatus: Int, override val title: Int) :
    SimpleListFragment<MyOrderListAllBean>(), MyOrderListLab, OnItemChildClickListener {

    companion object {
        fun newInstance(orderStatus: Int, title: Int): SubMyOrderAllFragment {
            val args = Bundle()
            val fragment = SubMyOrderAllFragment(orderStatus, title)
            fragment.arguments = args
            return fragment
        }
    }

    private val icon = AppGlobals.getApplication().getString(R.string.wallet_cny)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        isEnableLoadMore = false
        isAddDividerItemDecoration = false
    }


    override fun initView(view: View) {
        super.initView(view)
        mRecyclerView.setPadding(0, PixUtils.dp2px(10), 0, 0)
        mRecyclerView.clipToPadding = false

        mAdapter.addChildClickViewIds(
            R.id.mCancelOrder,
            R.id.toPaying,
            R.id.lookDelivery,
            R.id.onDeliveringDrawBack,
            R.id.mDelivered,
            R.id.onGoodsLaunchApplyDrawback,
            R.id.onGoodsLaunchMendSeller,
            R.id.onDeliveredApplyDrawback,
            R.id.onDeliveredToCommend,
        )
        mAdapter.setOnItemChildClickListener(this)
    }

    override fun getItemLayout(): Int {
        return R.layout.my_order_list_all_fragment
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: MyOrderListAllBean?) {

        val reference = item?.orderStatus
        val goodsStatusStr = when (reference) {
             ON_SENDING -> {
                "待发货"
            }
             ON_DELIVERY -> {
                "待收货"
            }
             ON_COMMENT -> {
                "待评价"
            }

             ON_COMMENTED -> {
                "已评价"
            }
             ON_DRAW_BACK -> {
                "申请退款"
            }
             ON_CANCEL -> {
                "取消"
            }
            else -> ""
        }

        val mXGridLayout: XGridLayout? = helper?.findView22(R.id.mXGridLayout)

        val mAdapter: CommAdapter<SstShopOrderChild> = object : CommAdapter<SstShopOrderChild>
            (_mActivity, R.layout.my_order_list_all_item_fragment) {
            override fun convert(
                holder: XQuickViewHolder?,
                item: SstShopOrderChild?,
                position: Int
            ) {
                holder?.setText(R.id.name, item?.goodsName)
                    ?.setText(R.id.typeTv, "${item?.goodsColor} ${item?.goodsSize}")
                    ?.setText(R.id.priceTv, "${item?.goodsPrice}")
                    ?.setText(R.id.countTv, "x${item?.goodsNums} ")
                    ?.displayImage(R.id.icon, item?.goodsLogo)
            }

        }
        mAdapter.addAll(item?.childOrds)
        mXGridLayout?.setAdapter(mAdapter, lifecycle)
        mXGridLayout?.maxItem=item?.childOrds?.size?:0

        helper?.setText(R.id.time, item?.createTime)
            ?.setText(R.id.decelerate, "共${item?.goodsNums}件商品，总金额：${item?.totalPrice} $icon")
            ?.setText(R.id.goodsStatus, goodsStatusStr)
            ?.setViewVisible(R.id.onPaying, reference ==  ON_SENDING)
            ?.setViewVisible(R.id.onDelivering, reference == ON_DELIVERY)
//            ?.setViewVisible(R.id.onGoodsLaunch, reference == MyOrderListAllBean.ON_COMMENT)
            ?.setViewVisible(R.id.onDelivered, reference ==  ON_COMMENT && item.isChild ==0)


    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(MyOrderListAllBean::class.java)
            .endSubType()
            .build()
    }

    override fun netRequest() {
//        val jsonFromRaw = Utils.getJsonFromRaw(_mActivity, R.raw.temp_fack_data)
//        parseDate("")

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "orderStatus" to orderStatus,
            "pageCount" to Int.MAX_VALUE,
            "pageIndex" to pageIndex,
            "uid" to userInfo?.uid,
        )
        RestClient.builder()
            .url(R.string.queryMyOrderList)
            .raw(JSON.toJSONString(map))
            .success { parseDate(it) }
            .failure { onFailed() }
            .error { _, _ -> onFailed() }
            .build().post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val orderList = obj["orderList"].toString()
        val array = JSON.parseArray(orderList, MyOrderListAllBean::class.java)
//        val ls = mutableListOf<SstShopOrderChild>()

        for (e in array) {
            if (e.isChild == 0) {
                val child = SstShopOrderChild()
                child.createTime = e.createTime
                child.goodsColor = e.goodsColor
                child.goodsId = e.goodsId
                child.goodsLogo = e.goodsLogo
                child.goodsName = e.goodsName
                child.goodsNums = e.goodsNums
                child.goodsPrice = e.goodsPrice
                child.orderId = e.orderId
                child.goodsSize = e.goodsSize
                child.orderStatus = e.orderStatus
                e.allCost = e.goodsPrice
                e.childOrds.add(child)

            } else if (e.isChild == 1) {
                var cost = 0.0
                for (en in e.childOrds) {
                    cost += en.goodsPrice * en.goodsNums
                }
                e.allCost = cost
            }
        }
        loadListDate(array)

    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.mCancelOrder -> {
                //取消订单

            }

            R.id.toPaying -> {
                //去支付
            }

            R.id.lookDelivery -> {
                //查看物流
            }

            R.id.onDeliveringDrawBack,
            R.id.onGoodsLaunchApplyDrawback,
            R.id.onDeliveredApplyDrawback -> {
                //申请退款

                start(DrawbackFragment.newInstance(item.orderId.toString()))
            }

            R.id.onGoodsLaunchMendSeller -> {
                //提醒卖家
            }

            R.id.mDelivered -> {
                //确认收货
                val map = mapOf(
                    "orderId" to item.orderId
                )
                RestClient.builder()
                    .raw(JSON.toJSONString(map))
                    .url(R.string.comfirmReceive)
                    .success {
                        if (!mSwipeRefreshLayout.isRefreshing){
                            mSwipeRefreshLayout.isRefreshing=true
                        }
                        onRefresh()
                    }.failure {
                        Toast.makeText(_mActivity,"发送失败",Toast.LENGTH_SHORT).show()
                    }.error { _, msg ->
                        Toast.makeText(_mActivity,msg,Toast.LENGTH_SHORT).show()
                    }.build().post()
            }

            R.id.onDeliveredToCommend -> {
                //去评价
                start(MyOrderCommentFragment.newInstance(item.orderId.toString()))
            }
        }
    }

    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        if (msg?.message == TO_REFRESH_LIST) {
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
            }
            onRefresh()
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        super.onItemClick(adapter, view, position)
        val item = mAdapter.getItem(position)
        start(MyOrderInfoFragment.newInstance(item.orderId.toString()))
    }


}